<!--
 * @Descripttion: 
 * @Version: 
 * @Author: gaohj
 * @Date: 2023-01-09 11:39:10
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-01-09 14:35:05
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //查询字符串和对象的相互转换
        var str1 = "https://www.qfedu.com/html5?username=zhangsan&password=123456&age=18#haha";
        // 步骤 
        // 1 将 张三给到 username 
        // 2 将 123456给到 password
        // 3 将 18给到 age

        // js的处理方式 可以 {username:'zhangsan',password:123456,age:18}
        // 然后将 {username:'zhangsan',password:123456,age:18}
        // 变成 username=zhangsan&password=123456&age=18
        // +
        // 字符串.concat(字符串)
        // 'https://www.qfedu.com/html5?'+'username=zhangsan&password=123456&age=18'+'#haha';

        // 关键问题 如何 将对象转成 'username=zhangsan&password=123456&age=18'
        // 1.将对象转成字符串 
        // 封装成一个函数 最后的结果是字符串 
        function obj_to_str(obj){
            var str = ''; // 准备一个空字符串 
            // 遍历对象 
            for(var k in obj){
                str += `${k}=${obj[k]}&`
            }
            str = str.slice(0,-1);
            return str;
        }
        var myobj = {username:'zhangsan',password:123456,age:18}
        console.log(obj_to_str(myobj))
        // 2.字符串转成对象
        // 封装成一个函数 最后的结果是对象

        // 'username=zhangsan&password=123456&age=18'
        function str_to_obj(str){
            var obj = {};
            // console.log(str.split('&'));
            // ['username=zhangsan','password=123456','age=18']
            var arr = str.split('&');
            // 遍历数组arr
            for(var k in arr){
                // console.log(arr[k]); // username=zhangsan
                var newarr = arr[k].split('=');
                // console.log(newarr); // ['username','zhangsan']
                obj[newarr[0]] = newarr[1];
            }
            return obj;
        }
        console.log(str_to_obj('username=zhangsan&password=123456&age=18'))
        //{username: 'zhangsan', password: '123456', age: '18'}
    </script>
</body>
</html>